﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Century.EnterpriseLibrary.Validation.DbProvider;
using Century.EnterpriseLibrary.Globalization;
using Century.Web.UI.MVC;

namespace Century.EnterpriseLibrary.Validation
{
    public class DynamicValidatorAdaptor : DataAnnotationsModelValidator<DynamicValidatorAttribute>
    {
        #region [ Constructor(s) ]

        public ValidationRule validationRule { get; set; }
        string fieldName, pageName, domain, className, action, controller;


        public DynamicValidatorAdaptor(ModelMetadata metadata, ControllerContext context, DynamicValidatorAttribute attribute)
            : base(metadata, context, attribute)
        {
            
            controller = System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"] == null ? string.Empty : System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
            action = System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values["Action"] == null ? string.Empty : System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values["Action"].ToString();
            pageName = controller + "." + action;
            fieldName = this.Metadata.PropertyName;
            className = this.Metadata.ContainerType.Name;
            domain = PersistData.CurrentSiteId.ToString();

            using (DbValidationContext db = new DbValidationContext())
            {
                validationRule = db.ValidationRules.Where(r =>
                       r.FieldName.ToLower() == fieldName.ToLower()
                    && r.EntityName.ToLower() == className.ToLower()
                    && r.PageName.ToLower() == pageName.ToLower()
                    && r.Domain.ToLower() == domain.ToLower()).FirstOrDefault();
            }
            if (validationRule != null)
            {
                attribute.validationRule = validationRule;
            }
        }

        #endregion

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {

            List<ModelClientValidationRule> rules = new List<ModelClientValidationRule>();
            ModelClientValidationRule rule = null;
           
            if (validationRule != null)
            {
                string errorMessageKey = string.Format("GLB.Validation.{0}.{1}.{2}.", domain, pageName, fieldName);
                string errorMessage = string.Empty;
                
                if (validationRule.IsRequired)
                {
                    errorMessageKey += "IsRequired";
                    errorMessage = GlobalizationManager.Translate(errorMessageKey, fieldName + " Is Required", FrameworkToken.UserToken.CurrentSite.Id);
                    if (this.Metadata.ModelType == typeof(bool) || this.Metadata.ModelType == typeof(bool?))
                    {
                        rule = new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = UIValidationType.checkrequired.ToString() };
                    }
                    else
                    {
                        rule = new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = UIValidationType.required.ToString() };
                    }
                    rules.Add(rule);
                }
                if (validationRule.MinLength.HasValue)
                {
                    errorMessageKey += "MinLength";
                    errorMessage = GlobalizationManager.Translate(errorMessageKey, fieldName + " Min Length: ", FrameworkToken.UserToken.CurrentSite.Id) + validationRule.MinLength.Value;

                    rule = new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = UIValidationType.minlen.ToString() };
                    rule.ValidationParameters.Add("min", validationRule.MinLength.Value);
                    rules.Add(rule);
                }
                if (validationRule.MaxLength.HasValue)
                {
                    errorMessageKey += "MaxMinLength";
                    errorMessage = GlobalizationManager.Translate(errorMessageKey, fieldName + " MAX Length: ", FrameworkToken.UserToken.CurrentSite.Id) + validationRule.MaxLength.Value;

                    rule = new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = UIValidationType.maxlen.ToString() };
                    rule.ValidationParameters.Add("max", validationRule.MaxLength.Value);
                    rules.Add(rule);
                }
                if (validationRule.Min.HasValue)
                {
                    errorMessageKey += "MinValue";
                    errorMessage = GlobalizationManager.Translate(errorMessageKey, fieldName + " Min value: ", FrameworkToken.UserToken.CurrentSite.Id) + validationRule.Min.Value;

                    rule = new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = UIValidationType.range.ToString() };
                    rule.ValidationParameters.Add("min", validationRule.Min.Value);
                    rules.Add(rule);
                }
                if (validationRule.Max.HasValue)
                {

                    errorMessageKey += "MaxValue";
                    errorMessage = GlobalizationManager.Translate(errorMessageKey, fieldName + " Max value: ", FrameworkToken.UserToken.CurrentSite.Id) + validationRule.Max.Value;
                    if (!validationRule.Min.HasValue)
                    {

                        rule = new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = UIValidationType.range.ToString() };
                        rules.Add(rule);
                        rule.ValidationParameters.Add("max", validationRule.Max.Value);

                    }
                }
                if (validationRule.IsNumber)
                {
                    errorMessageKey += "IsNumber";
                    errorMessage = GlobalizationManager.Translate(errorMessageKey, fieldName + " Should be a Number ", FrameworkToken.UserToken.CurrentSite.Id);

                    rule = new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = UIValidationType.number.ToString() };
                    rule.ValidationParameters.Add("isnumber", validationRule.IsNumber);
                    rules.Add(rule);

                }
                if (validationRule.IsEmail)
                {
                    errorMessageKey += "EmailFormat";
                    errorMessage = GlobalizationManager.Translate(errorMessageKey, fieldName + " is invalid E-mail ", FrameworkToken.UserToken.CurrentSite.Id);

                    rule = new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = UIValidationType.email.ToString() };
                    rules.Add(rule);
                }
                if (!string.IsNullOrEmpty(validationRule.RegExpression))
                {
                    rule = new ModelClientValidationRule() { ErrorMessage = validationRule.RegErrorMessage, ValidationType = UIValidationType.regex.ToString() };
                    rule.ValidationParameters.Add("pattern", validationRule.RegExpression);
                    rules.Add(rule);
                }



                return rules;
            }
            return rules;

        }

    }
}

